package com.unit6.lq.service;

import com.unit6.lq.util.GetConnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author 李琦 on 2021/8/20.
 * @version java version "16.0.1" 2021-04-20
 * 写登录,注册等方法
 */
public class UserService {
    //实例化放到方法里面,更加方便,不容易出错
//    static Connection conn=null;
//    static Statement stmt=null;

    //登录方法
    public static String login(String uname,String pwd)throws Exception{
        String msg="登陆失败";
        Connection conn= GetConnection.getConn();
        Statement stmt=conn.createStatement();
        String sql="select * from user where username='"+uname+"' and password='"+pwd+"'";
        ResultSet rs= stmt.executeQuery(sql);
        if(rs.next()){
            msg="登陆成功";
        }
        conn.close();
        stmt.close();
        return msg;
    }

    //注册方法
    public static String register(String uname,String pwd) throws Exception {
        String msg="注册失败";
        if("存在".equals(findUserName(uname))){
            msg="用户名已存在";
        }else{
            Connection conn= GetConnection.getConn();
            Statement stmt=conn.createStatement();
            String sql="insert into user(username,password) values('"+uname+"','"+pwd+"');";
            int count=stmt.executeUpdate(sql);//执行sql并返回受影响的
            if(count>0){
                msg="注册成功";
            }else{
                msg="sql执行错误,注册失败";
            }
            conn.close();
            stmt.close();
        }
        return msg;
    }
    //查询用户名是否存在
    public static String findUserName(String uname) throws Exception {
        String msg="不存在";
        Connection conn= GetConnection.getConn();
        Statement stmt=conn.createStatement();
        String sql="select *from user where username='"+uname+"'";
        ResultSet rs= stmt.executeQuery(sql);
        if(rs.next()){
            msg="存在";
        }
        conn.close();
        stmt.close();
        return msg;
    }

    //用户注销,需要验证密码
    public static String delUser(String uname,String pwd) throws Exception {
        String msg = "注销失败";
        if ("不存在".equals(findUserName(uname))) {
            msg = "用户名不存在";
        } else {
            if ("登陆成功".equals(login(uname,pwd))){
                Connection conn = GetConnection.getConn();
                Statement stmt = conn.createStatement();
                String sql="delete from user where username='"+uname+"'";
                int count=stmt.executeUpdate(sql);
                if (count > 0) {
                    msg="注销成功";
                }else{
                    msg="注销失败";
                }
                conn.close();
                stmt.close();
            }else{
                msg="密码验证失败";
            }

        }
        return msg;
    }

}
